//
//  KLMSigConnectManager.swift
//  KLM
//
//  Created by 朱雨 on 2023/6/7.
//

import UIKit
import nRFMeshProvision

class KLMSigConnectManager: NSObject {
    
    static let shared = KLMSigConnectManager()
    private override init(){}
    
    var command: KLMSigMeshCommand?
    var gattBearers: [PBGattBearer] = []
    
    ///开始连接
    func startConnect(discoveredPeripheral: DiscoveredPeripheral, commandResult: @escaping CommandResult) {
        if let bearer = gattBearers.first(where: {$0.identifier == discoveredPeripheral.peripheral.identifier}), bearer.isOpen {
            DispatchQueue.main.async {
                commandResult(true, nil)
            }
            return
        }
        let command = KLMSigMeshCommand()
        command.commandResult = commandResult
        self.command = command
        command.startTimer { [weak self] error in
            guard let self = self else { return }
            ///停止连接
            stopConnectDevcie(device: discoveredPeripheral)
            DispatchQueue.main.async {
                commandResult(false, error)
            }
        }
        
        let bb = PBGattBearer(target: discoveredPeripheral.peripheral)
        bb.logger = MeshNetworkManager.instance.logger
        bb.delegate = self
        bb.open()
        gattBearers.removeAll(where: {$0.identifier == discoveredPeripheral.peripheral.identifier})
        gattBearers.append(bb)
        KLMSigScanManager.shared.stopScanning()
    }
    
    ///停止所有的连接
    func stopConnectAllDevices() {
        gattBearers.forEach({$0.delegate = nil})
        gattBearers.forEach({$0.close()})
        gattBearers.removeAll()
    }
    ///停止某个连接
    func stopConnectDevcie(device: DiscoveredPeripheral) {
        gattBearers.first(where: {$0.identifier == device.peripheral.identifier})?.delegate = nil
        gattBearers.first(where: {$0.identifier == device.peripheral.identifier})?.close()
        gattBearers.removeAll(where: {$0.identifier == device.peripheral.identifier})
    }
}

extension KLMSigConnectManager: BearerDelegate {

    func bearerDidOpen(_ bearer: Bearer) {
        
        ///代理置为nil
        bearer.delegate = nil
        
        ///连接未配网成功
        if let bb:PBGattBearer = bearer as? PBGattBearer {
            
            KLMLog("connect Unprovision success - \(bb.identifier)")
            command?.commandResponseFinishWithCommand()
            if let resultCallback = command?.commandResult {
                DispatchQueue.main.async {
                    resultCallback(true, nil)
                }
            }
        }
    }

    func bearer(_ bearer: Bearer, didClose error: Error?) {
        
    }
}
